import requests
import datetime
from hashlib import md5
import re
import time
import pandas as pd
# from ChaoJiYing import Chaojiying_Client
import os


class DownData():
    """
    username:用户名
    password:密码
    captcha:验证码
    """

    def __init__(self, username, password, captcha):
        self.__username = username
        self.__password = password
        self.__captcha = captcha
        self.__url_login = 'http://49.232.189.50:8063/cptyc/login.action'
        self.__url_browse_list = 'http://49.232.189.50:8063/cptyc/complaints/cptBrowse/cptBrowseList.action'
        # 获取当前时间
        year = datetime.datetime.now().year
        month = datetime.datetime.now().month
        day = datetime.datetime.now().day
        now = f"{year}-{month}-{day}"
        # 设置参数
        self.currentPage = 1  # 当前页面
        self.pageSize = 200  # 每页显示的数据个数
        self.data_browse = {
            ' complaintInfo.cptCode': '',
            ' complaintInfo.cptCode': '2019-01-01',  # 查询开始时间
            'complaintInfo.cptTimeEnd': now,  # 查询结束时间
            'complaintInfo.cptSourceCode': '',
            'complaintInfo.disposeDept': '',
            'complaintInfo.currentPage': self.currentPage,
            'complaintInfo.pageSize': self.pageSize
        }
        # json数据列表，传入df_create（）获取结果
        self.__data_jsons = []

        self.__data = {
            'userInfo.loginName': self.__username,
            'userInfo.passWord': self.__password,
            'userInfo.captcha': self.__captcha
        }
        self.__headers = {
            'referer': 'http://49.232.189.50:8063/cptyc/login.action',
            'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1',
        }
        self.session = requests.session()

    def sessionCreate(self):
        # 创建回话，发送登录请求，取得验证码地址
        self.resp = self.session.post(
            self.__url_login, data=self.__data, headers=self.__headers).text
        part = r'(jcaptcha.jpg\??.*)" title="看不清,点击更换验证码"'
        jpg_adr = re.findall(part, self.resp)
        url_imge = f'http://49.232.189.50:8063/cptyc/{jpg_adr[0]}'

        # 用会话发送请求获取验证码
        img_data = self.session.get(url_imge, headers=self.__headers).content
        # 验证码储存至本地
        current_dir = os.path.dirname(os.path.abspath(__file__))
        par_dir = os.path.join(os.path.dirname(current_dir), 'assets')
        res_dir = os.path.join(par_dir, 'code.jpg')
        with open(res_dir, 'wb') as f:
            f.write(img_data)
        # with open('../assets/code.png', 'wb') as f2:
        #     f2.write(img_data)

    def setCaptcha(self, captcha):
        # 设置验证码
        self.__data['userInfo.captcha'] = captcha
        self.__catchSession()

    def setUsername(self, username):
        self.__data['userInfo.username'] = username

    def setPassword(self, password):
        self.__data['userInfo.password'] = password

    def getCatcha(self):
        return self.__data['userInfo.captcha']

    def setUser(self, username, password, captcha):
        self.__data['userInfo.loginName'] = username
        self.__data['userInfo.passWord'] = password
        self.__data['userInfo.captcha'] = captcha
        self.__catchSession()

    def getUser(self):
        return self.__data

    def chaoJiYing(self, username, password, code):
        """
        超级鹰官方网站:https://www.chaojiying.com
        超级鹰镜像网站:https://www.chaojiying.cn
        username：超级鹰用户名
        password：超级鹰密码
        code:用户中心>>软件ID 生成一个替换 96001
        """
        # 用户中心>>软件ID 生成一个替换 96001
        cjy = Chaojiying_Client(username, password, code)
        # 本地图片文件路径 来替换 a.jpg       有时WIN系统须要//
        im = open('./code.jpg', 'rb').read()
        self.captcha_text = cjy.PostPic(im, 1902)['pic_str'].upper()
        self.setCaptcha(self.captcha_text)

    def __catchSession(self):
        self.session.post(
            self.__url_login, data=self.__data, headers=self.__headers)

    def catchDataAll(self):
        while True:
            resp = self.session.post(
                self.__url_browse_list, data=self.data_browse, headers=self.__headers)
            data_json = resp.json()
            self.currentPage += 1
            self.data_browse['complaintInfo.currentPage'] = self.currentPage
            if data_json['rows'] == []:
                break
            self.__data_jsons.append(data_json)
        df_new = self.__getResultsToExcel(self.__data_jsons)
        return df_new.shape

    def catchDataUpdate(self):
        """
        更新数据
        """
        # 当前更新第几页
        self.data_browse['complaintInfo.currentPage'] = 1
        # 当前更新一页多少数据
        self.data_browse['complaintInfo.pageSize'] = 200
        # 数据表归零
        self.__data_jsons = []
        resp = self.session.post(
            self.__url_browse_list, data=self.data_browse, headers=self.__headers)
        data_json = resp.json()
        self.__data_jsons.append(data_json)
        df_new = self.__getResultsToExcel(self.__data_jsons)
        return df_new.shape

    def __getResultsToExcel(self, data_jsons):
        df_reses = []
        for data_json in data_jsons:
            df_reses.append(self.__df_create(data_json))
        df = pd.concat(df_reses, ignore_index=True)
        current_dir = os.path.dirname(os.path.abspath(__file__))
        par_dir = os.path.join(os.path.dirname(current_dir), 'datasets')
        res_dir = os.path.join(par_dir, '河东机场旅客投诉.xlsx')
        df_base = pd.read_excel(res_dir)
        df_new = pd.concat([df, df_base])
        df_new.drop_duplicates('投诉编号', inplace=True, keep='first')
        df_new.to_excel(res_dir, index=False)
        return df_new

    def __df_create(self, data_json):
        datas_dic = []
        for i in range(len(data_json['rows'])):
            datas_dic.append(data_json['rows'][i])
        df_lists = []
        for i in range(len(datas_dic)):
            # 获取数据分析字段
            df_dic = {}
            df_dic['投诉编号'] = [datas_dic[i]['cptCode']]
            df_dic['投诉时间'] = [datas_dic[i]['cptTime']]
            df_dic['投诉人'] = [datas_dic[i]['cptPerson']]
            df_dic['投诉来源'] = [datas_dic[i]['cptSourceName']]
            df_dic['投诉类型'] = [datas_dic[i]['cptTypeView']]
            df_dic['旅客诉求'] = [datas_dic[i]['cptAppeal']]
            df_dic['投诉内容'] = [datas_dic[i]['cptContent']]
            df_dic['处理部门'] = [datas_dic[i]['disposeDept']]
            df_dic['所属单位'] = [datas_dic[i]['arrAirportView']]
            df_dic['记录人'] = [datas_dic[i]['recordPerson']]
            df_dic['投诉状态'] = [datas_dic[i]['examineStateView']]
            df_lists.append(df_dic)
        df_all = []
        for df_list in df_lists:
            df = pd.DataFrame(df_list)
            df_all.append(df)
        df = pd.concat(df_all, ignore_index=True)
        return df


if __name__ == '__main__':
    current_dir = os.path.dirname(os.path.abspath(__file__))
    par_dir = os.path.join(os.path.dirname(current_dir), 'assets')
    res_dir = os.path.join(par_dir, 'code.jpg')
    print(res_dir)
